package com.chengqs.tomdog.connector;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;

public class HttpExchangeAdapter implements HttpExchangeRequest, HttpExchangeResponse{

    final HttpExchange exchange;
    byte[] requestBodyData;

    public HttpExchangeAdapter(HttpExchange exchange) {
        this.exchange = exchange;
    }

    /**
     * 从超类复制：
     *
     * 如果响应长度参数大于 {@code zero}，则指定
     * 要发送的确切字节数，并且应用程序必须发送该确切
     * 量的数据。如果响应长度参数为 {@code zero}，则使用
     * 分块传输编码，并且可以
     * 发送任意量的数据。应用程序通过关闭
     * {@link OutputStream} 来终止响应主体。
     */
    @Override
    public void sendResponseHeaders(int rCode, long responseLength) throws IOException {
        this.exchange.sendResponseHeaders(rCode, responseLength);
    }

    // 获取响应体输出流
    @Override
    public OutputStream getResponseBody() {
        return this.exchange.getResponseBody();
    }

    // 获取请求方法
    @Override
    public String getRequestMethod() {
        return this.exchange.getRequestMethod();
    }

    // 获取请求URI
    @Override
    public URI getRequestURI() {
        return this.exchange.getRequestURI();
    }

    // 获取请求头
    @Override
    public Headers getRequestHeaders() {
        return this.exchange.getRequestHeaders();
    }

    // 获取响应头
    @Override
    public Headers getResponseHeaders() {
        return this.exchange.getResponseHeaders();
    }

    @Override
    public InetSocketAddress getRemoteAddress() {
        return this.exchange.getRemoteAddress();
    }

    @Override
    public InetSocketAddress getLocalAddress() {
        return this.exchange.getLocalAddress();
    }

    // 获取请求体
    @Override
    public byte[] getRequestBody() throws IOException {
        if (this.requestBodyData == null) {
            // 通过输入流读取请求体
            try (InputStream input = this.exchange.getRequestBody()) {
                this.requestBodyData = input.readAllBytes();
            }
        }
        return this.requestBodyData;
    }
}
